package com.whj.wkpt.controller;

import com.whj.wkpt.entity.Task;
import com.whj.wkpt.entity.User;
import com.whj.wkpt.service.TaskService;
import com.whj.wkpt.service.UserService;
import com.whj.wkpt.validator.TaskValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Controller
@RequestMapping("/employer")
public class EmployerController {

    @Autowired
    private TaskService taskService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskValidator taskValidator;

    // 任务发布页面
    @GetMapping("/tasks/publish")
    public String publishTaskForm(Model model) {
        model.addAttribute("task", new Task());
        return "employer/task-form";
    }

    // 处理任务发布
    @PostMapping("/tasks")
    public String createTask(@ModelAttribute Task task, BindingResult bindingResult, Authentication authentication, Model model) {
        // 验证任务数据
        taskValidator.validate(task, bindingResult);
        
        if (bindingResult.hasErrors()) {
            return "employer/task-form";
        }
        
        // 获取当前登录用户
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username).orElse(null);
        
        if (currentUser != null) {
            task.setEmployerId(currentUser.getUserId());
            task.setTaskStatus("open"); // 默认状态为待承接
            task.setPublishDate(LocalDateTime.now()); // 设置发布时间
            taskService.createTask(task);
        }
        
        return "redirect:/employer/tasks";
    }

    // 任务编辑页面
    @GetMapping("/tasks/{taskId}/edit")
    public String editTaskForm(@PathVariable Long taskId, Model model) {
        Task task = taskService.findById(taskId);
        model.addAttribute("task", task);
        return "employer/task-form";
    }

    // 任务详情页面（查看功能）
    @GetMapping("/tasks/{taskId}")
    public String viewTask(@PathVariable Long taskId, Model model) {
        Task task = taskService.findById(taskId);
        model.addAttribute("task", task);
        return "employer/task-detail";
    }

    // 处理任务更新
    @PostMapping("/tasks/{taskId}")
    public String updateTask(@PathVariable Long taskId, @ModelAttribute Task task, BindingResult bindingResult) {
        // 验证任务数据
        taskValidator.validate(task, bindingResult);
        
        if (bindingResult.hasErrors()) {
            task.setTaskId(taskId);
            return "employer/task-form";
        }
        
        // 保留原有的雇主ID和发布时间，避免从前端传入的task对象中丢失该信息
        Task existingTask = taskService.findById(taskId);
        if (existingTask != null) {
            task.setEmployerId(existingTask.getEmployerId());
            task.setPublishDate(existingTask.getPublishDate()); // 保留原有的发布时间
        }
        
        task.setTaskId(taskId);
        taskService.updateTask(task);
        return "redirect:/employer/tasks";
    }

    // 删除任务
    @PostMapping("/tasks/{taskId}/delete")
    public String deleteTask(@PathVariable Long taskId) {
        taskService.deleteTask(taskId);
        return "redirect:/employer/tasks";
    }

    // 查看所有任务
    @GetMapping("/tasks")
    public String listTasks(Model model, Authentication authentication) {
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username).orElse(null);
        
        List<Task> tasks = null;
        if (currentUser != null) {
            tasks = taskService.findByEmployerId(currentUser.getUserId());
        }
        
        model.addAttribute("tasks", tasks);
        return "employer/task-list";
    }

    // 按标题搜索任务
    /**
     * 处理任务条件查询请求
     * 支持按任务标题和任务状态进行组合查询
     * 
     * @param title 任务标题查询条件（可选）
     * @param status 任务状态查询条件（可选）
     * @param model 视图模型
     * @param authentication 用户认证信息
     * @return 任务列表页面
     */
    @GetMapping("/tasks/search")
    public String searchTasks(@RequestParam(required = false) String title,
                              @RequestParam(required = false) String status,
                              Model model, Authentication authentication) {
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username).orElse(null);
        
        List<Task> tasks = null;
        if (currentUser != null) {
            // 调用Service层的条件查询方法
            tasks = taskService.searchTasks(currentUser.getUserId(), title, status);
        }
        
        model.addAttribute("tasks", tasks);
        model.addAttribute("searchTitle", title);
        model.addAttribute("searchStatus", status);
        return "employer/task-list";
    }
}